package qj.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import qj.ui.DesktopUI4;
import qj.util.funct.F1;
import qj.util.funct.P2;

public class EncryptUtil extends EncryptUtil4 {

	public static void editFile(File file, P2<byte[], Integer> act,
			F1<File, Boolean> fileCheck,
			F1<String, String> nameChange) {
		if (!file.exists()) {
			return;
		}
		if (file.isDirectory()) {
			File[] listFiles = file.listFiles();
			for (int i = 0; i < listFiles.length; i++) {
				File f = listFiles[i];
				editFile(f, act, fileCheck, nameChange);
			}
		} else {
			if (!fileCheck.e(file)) {
				return;
			}
			try {
				RandomAccessFile raf = new RandomAccessFile(file, "rwd");
				int bufferSize = 8192;
				byte[] buffer = new byte[bufferSize];
				for (int read, i = 0; (read = raf.read(buffer, 0, bufferSize)) > -1
						&& i < 500; i++) {
					act.e(buffer, read);
					raf.seek(raf.getFilePointer() - read);
					raf.write(buffer, 0, read);
				}
				raf.close();
			} catch (FileNotFoundException e) {
				throw new RuntimeException(e);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			file.renameTo(new File(file.getParentFile().getAbsolutePath() + "/"
					+ nameChange.e(file.getName())));
		}
	}

	public static void decryptL(File file) {
		editFile(file, new P2<byte[], Integer>() {
			public void e(byte[] a, Integer b) {
				decryptL(a, b);
			}
        }, new F1<File, Boolean>() {
			public Boolean e(File file) {
				return file.getName().endsWith(".qenc");
			}
        }, new F1<String, String>() {
			public String e(String obj) {
				return decrypt(obj
						.substring(0, obj.length() - ".qenc".length()));
			}
        });
	}

	public static void encryptL(File file) {
		editFile(file, new P2<byte[], Integer>() {
			public void e(byte[] a, Integer b) {
				encryptL(a, b);
			}
        }, new F1<File, Boolean>() {
			public Boolean e(File file) {
				return true;
			}
        }, new F1<String, String>() {
			public String e(String obj) {
				return encrypt(obj) + ".qenc";
			}
        });
	}


	
	public static void main(String[] args) {
		while (true) {
			String enc = DesktopUI4.prompt("");
			Clipboard.copy("\"" + decrypt(enc) + "\"");
		}
	}
}
